<script setup>
import MapContainer from '@/components/MapContainer.vue'
import MapShow from '@/components/MapShow.vue'
import { MapLocation, Hide, View } from '@element-plus/icons-vue'
import { doorplateQuery } from '@/api/doorplate';
import { getStreetList } from "@/api/street";
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from "vue";

const options = ref()
const mapVisible = ref(false)
const tempGeom = ref({
  lng: null,
  lat: null
})

const doorplates = ref([])
const mapShowVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const disable = ref(true)

const form = reactive({
  clazzId: null,
  divisionId: null,
  streetId: null,
  streetName: null,
  code: null,
  codeStatus: null,
  lng: null,
  lat: null,
  range: 3,
  pageNo: 1,
  pageSize: 10,
})

const showMap = () => {
  mapVisible.value = true;
}

const deleteGeom = () => {
  form.lng = null
  form.lat = null
  tempGeom.value.lng = null
  tempGeom.value.lat = null
  ElMessage.success('已清除选点')
}

const getStreets = () => {
  getStreetList().then((res) => {
    if (res.code === 0) {
      options.value = res.data.records
    } else {
      ElMessage.error(res.msg)
    }
  }).catch((error) => {
    console.error(error)
    ElMessage.error('获取街道列表失败')
  })
}

const handleLocation = (lng, lat) => {
  tempGeom.value.lng = lng
  tempGeom.value.lat = lat
}

const saveGeom = () => {
  if (tempGeom.value.lng && tempGeom.value.lat) {
    form.lng = tempGeom.value.lng
    form.lat = tempGeom.value.lat
    mapVisible.value = false
  } else {
    ElMessage.error('请先选择地图上的位置')
  }
}

const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？选择的地点将不会被保存。')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

const onSubmit = (data) => {
  doorplateQuery(data).then((res) => {
    if (res.code === 0) {
      // 处理查询结果
      doorplates.value = res.data.records.map((item, idx) => ({
        ...item,
        // 全局序号：当前页起始序号 + 本页索引
        seq: (res.data.current - 1) * res.data.size + idx + 1
      }))
      total.value = res.data.total
      currentPage.value = res.data.current
      pageSize.value = res.data.size
      if (total.value > 0) {
        disable.value = false
        ElMessage.success('查询成功')
      } else {
        disable.value = true
        ElMessage.warning('没有查询到相关门牌信息')
      }
    } else {
      ElMessage.error(res.msg)
    }
  }).catch((error) => {
    console.error(error)
    ElMessage.error('查询失败')
  })
}

const PageSizeChange = (value) => {
  form.pageNo = 1 // 重置页码为1
  form.pageSize = value
  onSubmit(form)
}
const PageCurrentChange = (value) => {
  form.pageNo = value
  onSubmit(form)
}

getStreets()

</script>


<template>
  <div>
    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <el-form-item label="门牌种类">
        <el-radio-group v-model="form.clazzId">
          <el-radio value="1" name="clazzId">
            居民楼
          </el-radio>
          <el-radio value="2" name="clazzId">
            商家
          </el-radio>
          <el-radio value="3" name="clazzId">
            公共设施
          </el-radio>
          <el-radio value="4" name="clazzId">
            其他
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="门牌地址">
        <el-select v-model="form.streetId" placeholder="请选择地址" filterable clearable>
          <el-option v-for="item in options" :key="item.id" :label="item.division.name + ' ' + item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="门牌号">
        <el-input v-model="form.code" placeholder="请输入号码" type="number" min="1" />
      </el-form-item>
      <el-form-item label="门牌状态">
        <el-radio-group v-model="form.codeStatus">
          <el-radio value="0" name="codeStatus">
            正常
          </el-radio>
          <el-radio value="1" name="codeStatus">
            损坏
          </el-radio>
          <el-radio value="2" name="codeStatus">
            丢失
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="地图选点">
        <el-button type="primary" @click="showMap" :icon="MapLocation">显示地图</el-button>
        <span v-if="form.lng && form.lat" style="margin-left: 10px">
          已选经纬度：{{ form.lng.toFixed(6) }}, {{ form.lat.toFixed(6) }}
        </span>
        <el-button type="danger" @click="deleteGeom" :disabled="!form.lng || !form.lat">清除选点</el-button>
      </el-form-item>
      <el-form-item label="范围（km）">
        <el-slider v-model="form.range" :min="1" :max="10" show-input />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(form)">查询</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="doorplates" style="width: 100%">
      <el-table-column label="序号" width="70" align="center">
        <template #default="{ $index }">
          {{ (currentPage - 1) * pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="divisionName" label="所属区划" />
      <el-table-column prop="streetName" label="所属街道" />
      <el-table-column prop="code" label="门牌号" />
      <el-table-column prop="clazzName" label="门牌种类" />
      <el-table-column prop="codeStatus" label="门牌状态">
        <template #default="scope">
          <span>{{ scope.row.codeStatus === "0" ? '正常' : scope.row.codeStatus === "1" ? '损坏' : '丢失' }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 2vmin">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[1, 2, 5, 10]"
        :background="true" layout="total, sizes, prev, pager, next, jumper" @size-change="PageSizeChange"
        @current-change="PageCurrentChange" :total="total" />
    </div>
    <div style="margin-top: 2vmin;">
      <div style="margin-bottom: 2vmin">
        <div style="color: dark-grey; display: inline-block">地图显示：</div>
        <el-switch v-model="mapShowVisible" inline-prompt :active-icon="View" :inactive-icon="Hide" :disabled="disable"
          size="large" />
      </div>
      <map-show v-if="doorplates.length > 0 && mapShowVisible" :zoom="12"
        style="width: 100%; height: 400px; border: 1px solid #dcdfe6; border-radius: 4px" :doorplates="doorplates" />
    </div>

    <el-dialog v-model="mapVisible" title="地图选点" width="500" :before-close="handleClose">
      <map-container v-if="mapVisible" style="width: 100%; height: 400px; border: 1px solid #dcdfe6; border-radius: 4px"
        :lng="form.lng" :lat="form.lat" @location-selected="handleLocation" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveGeom">
            确认
          </el-button>
          <el-button @click="mapVisible = false">取消</el-button>
        </div>
      </template>

    </el-dialog>
  </div>

</template>
